package _11_整理题目._6_模拟设计._竖式计算;

import org.apache.commons.lang.text.StrBuilder;
import org.junit.Test;

/**
 * 模拟 竖式加法计算过程
 *      使用两个指针 i j 分别从每个字符串尾部遍历，求和
 *      使用 StringBuilder 构建，最后翻转
 */
public class _03_字符串相加 {

    public String addStrings(String num1, String num2) {
        int i = num1.length()-1;
        int j = num2.length()-1;
        int add = 0;
        StrBuilder sb = new StrBuilder();
        while (i>=0 || j>=0 || add != 0) {
            int x = i>=0 ? num1.charAt(i)-'0' : 0;
            int y = j>=0 ? num2.charAt(j)-'0' : 0;
            int result = x + y + add;
            sb.append(result % 10);
            add = result / 10;
            i--; j--;
        }
        return sb.reverse().toString();
    }

    @Test
    public void main() {
        String num1 = "123";
        String num2 = "999";
        System.out.println(addStrings(num1, num2));
    }
}
